import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controller/auth_controller.dart';
import '../controller/wallet_controller.dart';
import '../widgets/login_dialog.dart';
import '../model/wallet_model.dart';
import '../screens/wallet/withdraw_page.dart';
import '../routes/app_routes.dart';

class WalletBottomSheet extends StatelessWidget {
  final AuthController authController = Get.find();
  final WalletController walletController;

  WalletBottomSheet({required this.walletController});

  @override
  Widget build(BuildContext context) {
    final screenHeight = MediaQuery.of(context).size.height;
    final screenWidth = MediaQuery.of(context).size.width;
    final isSmallScreen = screenHeight < 700 || screenWidth < 360;
    final isVerySmallScreen = screenHeight < 600 || screenWidth < 320;
    
    // 响应式间距和尺寸
    final horizontalPadding = isVerySmallScreen ? 12.0 : (isSmallScreen ? 16.0 : 20.0);
    final verticalSpacing = isVerySmallScreen ? 12.0 : (isSmallScreen ? 16.0 : 20.0);
    
    return Container(
      constraints: BoxConstraints(
        maxHeight: screenHeight * (isVerySmallScreen ? 0.9 : 0.85),
        minHeight: isSmallScreen ? screenHeight * 0.6 : 400,
      ),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Color(0xFF1B3B36), // 深绿色
            Color(0xFF0F2027), // 更深的绿色
          ],
        ),
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 拖拽手柄
          _buildDragHandle(),
          
          // 标题栏
          _buildHeader(),
          
          // 内容区域 - 可滚动
          Flexible(
            child: SingleChildScrollView(
              physics: AlwaysScrollableScrollPhysics(),
              padding: EdgeInsets.symmetric(horizontal: 15),
              child: Column(
                children: [
                  SizedBox(height: verticalSpacing * 2),
                  _buildBalanceCard(),
                  SizedBox(height: verticalSpacing),
                  _buildClaimRewardsButton(),
                  SizedBox(height: 15),
                  _buildViewAllButton(),
                  SizedBox(height: verticalSpacing),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDragHandle() {
    return Container(
      margin: EdgeInsets.only(top: 8, bottom: 4),
      width: 40,
      height: 4,
      decoration: BoxDecoration(
        color: Colors.grey[600],
        borderRadius: BorderRadius.circular(2),
      ),
    );
  }

  Widget _buildHeader() {
    return Builder(
      builder: (context) {
        final screenWidth = MediaQuery.of(context).size.width;
        final isVerySmallScreen = screenWidth < 320;
        final isSmallScreen = screenWidth < 360;
        
        return Container(
          padding: EdgeInsets.symmetric(
            horizontal: isVerySmallScreen ? 12 : (isSmallScreen ? 16 : 20), 
            vertical: isVerySmallScreen ? 12 : 16
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Column(
                children: [
                  Text(
                    'Wallet',
                    style: TextStyle(
                      color: Color(0xFFE6B450), // 金色
                      fontSize: isVerySmallScreen ? 20 : (isSmallScreen ? 22 : 24),
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  SizedBox(height: 4),
                  Obx(() {
                    return Text(
                      'ID: ${authController.userId.isNotEmpty ? authController.userId : '911453'}',
                      style: TextStyle(
                        color: Colors.grey[400],
                        fontSize: isVerySmallScreen ? 12 : 14,
                      ),
                    );
                  }),
                ],
              ),
            ],
          ),
        );
      }
    );
  }

  Widget _buildBalanceCard() {
    return Builder(
      builder: (context) {
        final screenWidth = MediaQuery.of(context).size.width;
        final isVerySmallScreen = screenWidth < 320;
        final isSmallScreen = screenWidth < 360;
        
        return Container(
          width: double.infinity,
          padding: EdgeInsets.all(isVerySmallScreen ? 16 : (isSmallScreen ? 20 : 24)),
          decoration: BoxDecoration(
            color: Colors.transparent,
            borderRadius: BorderRadius.circular(12),
          ),
          child: Column(
            children: [
              Text(
                'Total Assets (BTC)',
                style: TextStyle(
                  color: Color(0xFFE6B450), // 金色
                  fontSize: isVerySmallScreen ? 14 : 16,
                ),
              ),
              SizedBox(height: isVerySmallScreen ? 8 : 12),
              Obx(() {
                final balance = walletController.availableBalance;
                return Text(
                  balance.isNotEmpty ? balance : '0.00000002095289',
                  style: TextStyle(
                    color: Color(0xFFE6B450), // 金色
                    fontSize: isVerySmallScreen ? 20 : (isSmallScreen ? 24 : 28),
                    fontWeight: FontWeight.bold,
                  ),
                  textAlign: TextAlign.center,
                );
              }),
            ],
          ),
        );
      }
    );
  }

  Widget _buildClaimRewardsButton() {
    return Builder(
      builder: (context) {
        final screenWidth = MediaQuery.of(context).size.width;
        final isVerySmallScreen = screenWidth < 320;
        final isSmallScreen = screenWidth < 360;
        final horizontalMargin = isVerySmallScreen ? 8.0 : (isSmallScreen ? 12.0 : 20.0);
        
        return Container(
          width: double.infinity,
          height: isVerySmallScreen ? 48 : 56,
          margin: EdgeInsets.symmetric(horizontal: horizontalMargin),
          child: ElevatedButton(
            onPressed: () {
              Get.back();
              if (authController.isLoggedIn.value) {
                Get.toNamed(AppRoutes.withdraw);
              } else {
                Get.dialog(LoginDialog());
              }
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Color(0xFFE6B450), // 金色背景
              foregroundColor: Colors.black, // 黑色文字
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(28),
              ),
              elevation: 0,
            ),
            child: Text(
              'Claim Rewards',
              style: TextStyle(
                fontSize: isVerySmallScreen ? 16 : 18,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        );
      }
    );
  }

  Widget _buildViewAllButton() {
    return Builder(
      builder: (context) {
        final screenWidth = MediaQuery.of(context).size.width;
        final isVerySmallScreen = screenWidth < 320;
        
        return Container(
          margin: EdgeInsets.symmetric(horizontal: 0),
          child: TextButton(
            onPressed: () {
              Get.back();
              Get.toNamed('/records-detail');
            },
            child: Text(
              'View All',
              style: TextStyle(
                color: Color(0xFFE6B450), // 金色
                fontSize: isVerySmallScreen ? 14 : 16,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        );
      }
    );
  }

  Widget _buildRecentRecords() {
    return Builder(
      builder: (context) {
        final screenWidth = MediaQuery.of(context).size.width;
        final isVerySmallScreen = screenWidth < 320;
        final isSmallScreen = screenWidth < 360;
        final horizontalMargin = 15.0;
        
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: EdgeInsets.symmetric(horizontal: isVerySmallScreen ? 12 : 16),
              child: Text(
                'Recent Records',
                style: TextStyle(
                  color: Color(0xFFE6B450), // 金色
                  fontSize: isVerySmallScreen ? 16 : 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            SizedBox(height: isVerySmallScreen ? 12 : 16),
            Obx(() {
              if (walletController.isLoadingRecentRecords.value) {
                return Center(
                  child: CircularProgressIndicator(
                    valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFE6B450)),
                  ),
                );
              }

              if (walletController.recentRecords.isEmpty) {
                return Container(
                  padding: EdgeInsets.all(isVerySmallScreen ? 24 : 40),
                  child: Center(
                    child: Text(
                      'No records yet',
                      style: TextStyle(
                        color: Colors.grey[400],
                        fontSize: isVerySmallScreen ? 14 : 16,
                      ),
                    ),
                  ),
                );
              }

              // 显示最多3条记录
              final displayRecords = walletController.recentRecords.take(3).toList();
              
              return Column(
                children: [
                  ...displayRecords.map((record) => Container(
                    margin: EdgeInsets.symmetric(horizontal: 0, vertical: 6),
                    padding: EdgeInsets.all(isVerySmallScreen ? 12 : 16),
                    decoration: BoxDecoration(
                      color: Colors.transparent,
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Row(
                      children: [
                        Container(
                          width: isVerySmallScreen ? 32 : 40,
                          height: isVerySmallScreen ? 32 : 40,
                          decoration: BoxDecoration(
                            color: Color(0xFFE6B450).withOpacity(0.2),
                            borderRadius: BorderRadius.circular(isVerySmallScreen ? 16 : 20),
                          ),
                          child: Icon(
                            Icons.settings,
                            color: Color(0xFFE6B450),
                            size: isVerySmallScreen ? 16 : 20,
                          ),
                        ),
                        SizedBox(width: isVerySmallScreen ? 8 : 12),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                'Plan Income',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 13,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                              SizedBox(height: 4),
                              Text(
                                '2025-09-16 11:00',
                                style: TextStyle(
                                  color: Colors.grey[400],
                                  fontSize: 11,
                                ),
                              ),
                            ],
                          ),
                        ),
                        Text(
                          '+0.00000001186 BTC',
                          style: TextStyle(
                            color: Color(0xFF4ECDC4), // 绿色
                            fontSize: 10,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ],
                    ),
                  )).toList(),
                  SizedBox(height: isVerySmallScreen ? 6 : 8),
                  Container(
                    margin: EdgeInsets.symmetric(horizontal: 0),
                    child: TextButton(
                      onPressed: () {
                        Get.back();
                        Get.toNamed('/wallet');
                      },
                      child: Text(
                        'View All',
                        style: TextStyle(
                          color: Color(0xFFE6B450), // 金色
                          fontSize: isVerySmallScreen ? 14 : 16,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ),
                ],
              );
            }),
          ],
        );
      }
    );
  }

  Widget _buildEmptyState() {
    return Builder(
      builder: (context) {
        final screenWidth = MediaQuery.of(context).size.width;
        final isVerySmallScreen = screenWidth < 320;
        final isSmallScreen = screenWidth < 360;
        
        return Container(
          padding: EdgeInsets.all(isVerySmallScreen ? 24 : 32),
          child: Center(
            child: Column(
              children: [
                Icon(
                  Icons.inbox_outlined,
                  color: Colors.grey[400],
                  size: isVerySmallScreen ? 40 : 48,
                ),
                SizedBox(height: isVerySmallScreen ? 12 : 16),
                Text(
                  'No Records Available'.tr,
                  style: TextStyle(
                    color: Colors.grey[400], 
                    fontSize: isVerySmallScreen ? 14 : 16
                  ),
                ),
                SizedBox(height: 8),
                Text(
                  'Your transaction records will appear here',
                  style: TextStyle(
                    color: Colors.grey[500], 
                    fontSize: isVerySmallScreen ? 12 : 14
                  ),
                  textAlign: TextAlign.center,
                ),
              ],
            ),
          ),
        );
      }
    );
  }

  Widget _buildLoadingState() {
    return Builder(
      builder: (context) {
        final screenWidth = MediaQuery.of(context).size.width;
        final isVerySmallScreen = screenWidth < 320;
        
        return Container(
          padding: EdgeInsets.all(isVerySmallScreen ? 24 : 32),
          child: Center(
            child: Column(
              children: [
                SizedBox(
                  width: isVerySmallScreen ? 20 : 24,
                  height: isVerySmallScreen ? 20 : 24,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.orange),
                  ),
                ),
                SizedBox(height: isVerySmallScreen ? 12 : 16),
                Text(
                  'Loading records...',
                  style: TextStyle(
                    color: Colors.grey[400], 
                    fontSize: isVerySmallScreen ? 12 : 14
                  ),
                ),
              ],
            ),
          ),
        );
      }
    );
  }

  Widget _buildRecordItem(RecentRecordModel record) {
    return Builder(
      builder: (context) {
        final screenWidth = MediaQuery.of(context).size.width;
        final isVerySmallScreen = screenWidth < 320;
        final isSmallScreen = screenWidth < 360;
        
        return Container(
          padding: EdgeInsets.symmetric(vertical: isVerySmallScreen ? 8 : 12),
          decoration: BoxDecoration(
            border: Border(
              bottom: BorderSide(color: Color(0xFF2A2A2A), width: 0.5),
            ),
          ),
          child: Row(
            children: [
              Container(
                width: isVerySmallScreen ? 28 : 36,
                height: isVerySmallScreen ? 28 : 36,
                decoration: BoxDecoration(
                  color: record.statusColor.withOpacity(0.2),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Icon(
                  record.typeIcon, 
                  color: record.statusColor, 
                  size: isVerySmallScreen ? 14 : 18
                ),
              ),
              SizedBox(width: isVerySmallScreen ? 8 : 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      record.title,
                      style: TextStyle(
                        color: Colors.white, 
                        fontSize: isVerySmallScreen ? 12 : 14
                      ),
                    ),
                    SizedBox(height: 2),
                    Text(
                      '${record.formattedDate} ${record.formattedTime}',
                      style: TextStyle(
                        color: Colors.grey[400], 
                        fontSize: isVerySmallScreen ? 10 : 12
                      ),
                    ),
                  ],
                ),
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Text(
                    '${record.displayAmount >= 0 ? '+' : ''}${record.displayAmount.toStringAsFixed(12)}BTC',
                    style: TextStyle(
                      color: record.displayAmount >= 0 ? Colors.green : Colors.red,
                      fontSize: isVerySmallScreen ? 10 : 12,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
              ),
            ],
          ),
        );
      }
    );
  }

  static void show() {
    // 确保 WalletController 已注册并初始化
    if (!Get.isRegistered<WalletController>()) {
      Get.put(WalletController());
    }
    final walletController = Get.find<WalletController>();
    walletController.refreshAllData();
    
    Get.bottomSheet(
      WalletBottomSheet(walletController: walletController),
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      enableDrag: true,
    );
  }
}